/*----------------------------------------------------------\\
|| Mancala                                                  ||
|| CS-340 with Professor Troy                               ||
|| Joshua Jung and Eugene Magdel                            ||
|| April 29, 2011                                           ||
\\----------------------------------------------------------*/
#include "highscore.h"

//Adds highscore into the list
void Highscore::add(string name, int score){
  ofstream highscore_file;
  highscore_file.open(SCORE_FILE, ios::out | ios::app);
  highscore_file << name << ";" << score << "\n";
  highscore_file.close();
}

//TODO figure out return array of pointers of objects crap
//For now alters the passed array, fills it up sorted with scores
void Highscore::top(int number, Score** scores){
for(int i=0; i< number; i++)
    scores[i] = NULL;


  list<Score*> content;
  ifstream infile;

  infile.open(SCORE_FILE);
  while (!infile.eof()){
   if(infile.good()){
    char line[256];

    infile >> line;
    stringstream stream;
    stream << line;
    string partial = "";
    string name = "";
    int score = 0;
    int i = 0;
    while(getline(stream, partial, ';')){
      if(i==0) name = partial;
      else if(i==1) score = atoi(partial.c_str());
      i++;
    }
    //cout << "name is : " << name << " score " << score << endl;
    content.push_back(new Score(name, score));
    }
   }
  if(content.size() > 0)
    content.pop_back();
  content.sort(compare_score);
  infile.close();
  int number_of_scores = number;
  if(content.size() < number_of_scores)
    number_of_scores = content.size();
  //Score** scores = new Score*[number_of_scores];
  int i = 0;
  for(list<Score*>::iterator s = content.begin(); s != content.end() && i < 5; ++s){
    scores[i] = *s;
    i++;
  }
}

void Highscore::clear_scores(){
  remove(SCORE_FILE);
}

Score::Score(string _name, int _score): name(_name), score(_score){ }

//Used for sorting
bool compare_score(Score* l, Score* r) {
  return l -> score > r -> score;
}

bool Highscore::is_top_5_score(int s){
    Score** scores = new Score*[5];
    Highscore::top(5, scores);
    int j=0;
    for(int i=0; i<5; i++){
        if(scores[i] == NULL)
            break;
        j++;
    }
    if(j<=4)
        return true;
    //Greater than the lowest out of 5 scores
    return s>scores[4] -> score;
}

